// 用户管理模块
const state = {
  // 用户信息
  userInfo: {
    id: null,
    username: '',
    nickname: '',
    avatar: '',
    role: 'guest',
    permissions: []
  },

  // 认证状态
  isAuthenticated: false,

  // 登录状态
  loginLoading: false,

  // 用户偏好设置
  preferences: {
    theme: 'dark',
    language: 'zh-CN',
    autoUpdate: true
  }
}

const getters = {
  // 获取用户信息
  userInfo: state => state.userInfo,

  // 是否已认证
  isAuthenticated: state => state.isAuthenticated,

  // 是否是管理员
  isAdmin: state => state.userInfo.role === 'admin',

  // 获取用户昵称，如果没有则返回用户名
  displayName: state => state.userInfo.nickname || state.userInfo.username || '游客',

  // 获取用户头像
  userAvatar: state => state.userInfo.avatar || '/default-avatar.png',

  // 获取用户偏好
  userPreferences: state => state.preferences,

  // 登录是否加载中
  loginLoading: state => state.loginLoading
}

const mutations = {
  // 设置用户信息
  SET_USER_INFO(state, userInfo) {
    state.userInfo = { ...state.userInfo, ...userInfo }
  },

  // 设置认证状态
  SET_AUTHENTICATED(state, isAuthenticated) {
    state.isAuthenticated = isAuthenticated
  },

  // 设置登录加载状态
  SET_LOGIN_LOADING(state, loading) {
    state.loginLoading = loading
  },

  // 更新用户偏好
  UPDATE_PREFERENCES(state, preferences) {
    state.preferences = { ...state.preferences, ...preferences }
    // 持久化到本地存储
    localStorage.setItem('userPreferences', JSON.stringify(state.preferences))
  },

  // 清除用户信息
  CLEAR_USER_INFO(state) {
    state.userInfo = {
      id: null,
      username: '',
      nickname: '',
      avatar: '',
      role: 'guest',
      permissions: []
    }
    state.isAuthenticated = false
  }
}

const actions = {
  // 检查认证状态
  checkAuth({ commit }) {
    return new Promise((resolve) => {
      // 检查本地存储中的token
      const token = localStorage.getItem('authToken')
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || 'null')
      const preferences = JSON.parse(localStorage.getItem('userPreferences') || '{}')

      if (token && userInfo) {
        commit('SET_USER_INFO', userInfo)
        commit('SET_AUTHENTICATED', true)
        commit('UPDATE_PREFERENCES', preferences)
        resolve(true)
      } else {
        commit('CLEAR_USER_INFO')
        resolve(false)
      }
    })
  },

  // 用户登录
  async login({ commit }, credentials) {
    commit('SET_LOGIN_LOADING', true)

    try {
      // 模拟登录API调用
      const response = await new Promise((resolve, reject) => {
        setTimeout(() => {
          // 简单的模拟登录逻辑
          if (credentials.username && credentials.password) {
            let userInfo = {}

            // 根据用户名设置不同的用户信息
            if (credentials.username === 'admin') {
              userInfo = {
                id: 1,
                username: credentials.username,
                nickname: '系统管理员',
                avatar: '',
                role: 'admin',
                permissions: ['read', 'write', 'admin']
              }
            } else if (credentials.username === 'detention-admin') {
              userInfo = {
                id: 2,
                username: credentials.username,
                nickname: '收押分流管理员',
                avatar: '',
                role: 'detention-admin',
                permissions: ['read', 'write', 'detention']
              }
            } else {
              // 其他账号使用默认信息
              userInfo = {
                id: 999,
                username: credentials.username,
                nickname: '普通用户',
                avatar: '',
                role: 'user',
                permissions: ['read']
              }
            }

            resolve({
              token: 'mock-jwt-token',
              user: userInfo
            })
          } else {
            reject(new Error('用户名或密码错误'))
          }
        }, 1000)
      })

      // 保存token和用户信息
      localStorage.setItem('authToken', response.token)
      localStorage.setItem('userInfo', JSON.stringify(response.user))

      commit('SET_USER_INFO', response.user)
      commit('SET_AUTHENTICATED', true)

      return response

    } catch (error) {
      throw error
    } finally {
      commit('SET_LOGIN_LOADING', false)
    }
  },

  // 用户登出
  logout({ commit }) {
    // 清除本地存储
    localStorage.removeItem('authToken')
    localStorage.removeItem('userInfo')

    commit('CLEAR_USER_INFO')
  },

  // 更新用户信息
  updateUserInfo({ commit }, userInfo) {
    commit('SET_USER_INFO', userInfo)
    // 同步到本地存储
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  },

  // 更新用户偏好
  updatePreferences({ commit }, preferences) {
    commit('UPDATE_PREFERENCES', preferences)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}

